package com.hhh.tools.ui.screens

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context.CLIPBOARD_SERVICE
import android.text.TextUtils
import android.util.Base64
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.hhh.tools.ui.components.AppTitle
import com.hhh.tools.ui.navigation.Destinations
import com.hhh.tools.ui.theme.ComposeDemoTheme
import com.hhh.tools.viewmodel.Base64ViewModel

@Preview
@Composable
fun PreviewBase64Page() {
    val navController = rememberNavController()
    Base64Page(navController)
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun Base64Page(navController: NavController) {
    ComposeDemoTheme {
        Column(
            Modifier
                .background(MaterialTheme.colors.background)
                .fillMaxSize()
        ) {
            val context = LocalContext.current

            val model = viewModel<Base64ViewModel>()
            val text: String by model.input.observeAsState("")
            val showContent: Boolean by model.show.collectAsState()
            val content: String by model.content.observeAsState("")

            AppTitle("Base64转码") {
                navController.popBackStack()
            }

            Spacer(modifier = Modifier.height(10.dp))

            InputContent(text, "输入需要Base64编码的内容", onValueChange = {
                model.onInputChange(it)
            })

            Log.e("hhh", "showContent = $showContent content=$content")
            if (showContent) {
                Spacer(modifier = Modifier.height(10.dp))

                Text(
                    text = if (!TextUtils.isEmpty(content)) content else "",
                    modifier = Modifier
                        .fillMaxWidth()
                        .heightIn(100.dp)
                        .padding(horizontal = 14.dp)
                        .combinedClickable(onDoubleClick = {
                            navController.navigate(Destinations.CopyContentPage.route + "/${content}")
                        }, indication = null, interactionSource = remember {
                            MutableInteractionSource()
                        }) {
                        }
                        .background(color = Color.White, shape = RoundedCornerShape(7.dp))
                        .padding(10.dp, 5.dp)
                )
            }

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(0.dp, 10.dp, 14.dp, 0.dp),
                horizontalArrangement = Arrangement.End
            ) {
                if (!TextUtils.isEmpty(text)) {
                    OptionBtn("清空") {
                        model.onInputChange("")
                    }
                }
                Spacer(modifier = Modifier.width(14.dp))
                OptionBtn("粘贴") {
                    val cm = context.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
                    val clip = cm.primaryClip
                    if (null != clip && clip.itemCount > 0) {
                        val coerceToText = clip.getItemAt(0).coerceToText(context)
                        if (!TextUtils.isEmpty(coerceToText)) {
                            model.onInputPlus(coerceToText.toString().trim())
                        } else {
                            Toast.makeText(context, "内容为空", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
                if (showContent) {
                    Spacer(modifier = Modifier.width(14.dp))
                    OptionBtn("复制") {
                        if (TextUtils.isEmpty(content)) {
                            Toast.makeText(context, "内容为空", Toast.LENGTH_SHORT).show()
                        } else {
                            Log.e("hhh", content)
                            val cm = context.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
                            cm.setPrimaryClip(ClipData.newPlainText(context.packageName, content))
                            Toast.makeText(context, "复制成功", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }

            Spacer(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
            )

            TransCodeBtn("BASE64加密", onClick = {
                if (text.isNotEmpty()) {
                    model.setShowContent(true)

                    model.onContentChange(Base64.encodeToString(text.toByteArray(), Base64.DEFAULT))
                } else {
                    Toast.makeText(context, "内容为空", Toast.LENGTH_SHORT).show()
                }
            })

            Spacer(modifier = Modifier.height(10.dp))

            TransCodeBtn("BASE64解密", onClick = {
                if (text.isNotEmpty()) {
                    model.setShowContent(true)

                    model.onContentChange(String(Base64.decode(text.toByteArray(), Base64.DEFAULT)))
                } else {
                    Toast.makeText(context, "内容为空", Toast.LENGTH_SHORT).show()
                }
            })

            Spacer(modifier = Modifier.height(10.dp))
        }
    }
}

@Composable
fun InputContent(text: String, hint: String, onValueChange: (String) -> Unit) {
    TextField(
        value = text,
        modifier = Modifier
            .fillMaxWidth()
            .heightIn(100.dp)
            .padding(horizontal = 14.dp),
        onValueChange = onValueChange,
        placeholder = @Composable {
            Text(text = hint)
        },
        maxLines = 10,
        shape = RoundedCornerShape(7.dp),
        isError = false,
        colors = TextFieldDefaults.textFieldColors(
            backgroundColor = Color.White,
            focusedIndicatorColor = Color.Transparent,         //有焦点的边框颜色
            unfocusedIndicatorColor = Color.Transparent, // 无焦点时的颜色，绿色
            errorIndicatorColor = Color.Red, // 错误时的颜色，红色
            disabledIndicatorColor = Color.Gray, // 不可用时的颜色，灰色
            cursorColor = Color.Blue
        ),
        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Go)
    )
}

@Composable
fun OptionBtn(text: String, onClick: () -> Unit) {
    Button(
        onClick = onClick, modifier = Modifier
            .height(30.dp)
            .width(80.dp),
        contentPadding = PaddingValues(0.dp)
    ) {
        Text(text = text, fontSize = 14.sp)
    }
}

@Composable
fun TransCodeBtn(text: String, onClick: () -> Unit) {
    Button(
        onClick = onClick,
        modifier = Modifier
            .fillMaxWidth()
            .height(44.dp)
            .padding(horizontal = 14.dp),
        shape = RoundedCornerShape(7.dp)
    ) {
        Text(text = text)
    }
}

